//
//  YCPermissionManager.swift
//  YCLiveStreaming
//
//  Created by Billy on 2024/10/17.
//

import UIKit
import AVFoundation
import Photos

open class YCPermissionManager {
    
    @objc static func checkCameraAuthorized(parent: UIViewController, completion: ((Bool) -> Void)? = nil) {
        requestCapturePermission { granted in
            if !granted {
                showAuthorizedFail(parent: parent, message: "摄像头权限未开启，请开启摄像头权限")
            }
            completion?(granted)
        }
    }
    
    @objc static func checkAudioAuthorized(parent: UIViewController, completion: ((Bool) -> Void)? = nil) {
        requestAudioSession { granted in
            if !granted {
                showAuthorizedFail(parent: parent, message: "麦克风权限未开启，请开启麦克风权限")
            }
            completion?(granted)
        }
    }
    
    @objc static func checkPhotoLibraryAuthorized(parent: UIViewController, completion: ((Bool) -> Void)? = nil) {
        requestPhotoLibraryPermission { granted in
            if !granted {
                showAuthorizedFail(parent: parent, message: "相册权限未开启，请开启相册权限")
            }
            completion?(granted)
        }
    }
        
    /// 请求摄像头权限
    @objc static func requestCapturePermission(completion: @escaping(Bool) -> Void) {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        
        // 如果权限被拒绝或限制
        if status == .denied || status == .restricted {
            DispatchQueue.main.async {
                completion(false)
            }
            return
        }
        
        // 如果权限已经授权
        if status == .authorized {
            DispatchQueue.main.async {
                completion(true)
            }
            return
        }
        
        // 请求摄像头权限
        AVCaptureDevice.requestAccess(for: .video) { granted in
            DispatchQueue.main.async {
                completion(granted)
            }
        }
    }
    
    /// 请求麦克风权限
    /// - Parameter completion: 请求结果，返回 `true` 表示授权成功，返回 `false` 表示授权失败
    @objc static func requestAudioSession(completion: @escaping (Bool) -> Void) {
        // 获取麦克风权限状态
        let status = AVCaptureDevice.authorizationStatus(for: .audio)
        
        // 判断当前权限状态
        switch status {
        case .denied, .restricted:
            // 用户拒绝或权限受限，直接返回失败
            DispatchQueue.main.async {
                completion(false)
            }
            return
            
        case .authorized:
            // 用户已授权，直接返回成功
            DispatchQueue.main.async {
                completion(true)
            }
            return
            
        case .notDetermined:
            // 尚未决定权限状态，进一步检查录音权限
            let permissionStatus = AVAudioSession.sharedInstance().recordPermission
            
            // 如果权限未决定，请求权限
            if permissionStatus == .undetermined {
                AVAudioSession.sharedInstance().requestRecordPermission { granted in
                    DispatchQueue.main.async {
                        completion(granted)
                    }
                }
            } else {
                // 用户已经决定了权限，直接返回权限状态
                DispatchQueue.main.async {
                    completion(permissionStatus == .granted)
                }
            }
        @unknown default:
            // 处理未来可能出现的权限状态
            DispatchQueue.main.async {
                completion(false)
            }
        }
    }
    
    /// 请求相册权限
    @objc static func requestPhotoLibraryPermission(completion: @escaping (Bool) -> Void) {
        
        let status = PHPhotoLibrary.authorizationStatus()
        
        switch status {
        case .authorized:
            // 已经授权
            DispatchQueue.main.async {
                completion(true)
            }
            break
        case .denied, .restricted:
            // 用户拒绝或权限受限
            DispatchQueue.main.async {
                completion(false)
            }
            break
        case .notDetermined:
            // 尚未决定，进行请求
            PHPhotoLibrary.requestAuthorization { newStatus in
                DispatchQueue.main.async {
                    completion(newStatus == .authorized)
                }
            }
            break
        @unknown default:
            // 处理未来可能出现的权限状态
            DispatchQueue.main.async {
                completion(false)
            }
            break
        }
    }

    
    @objc static func showAuthorizedFail(parent: UIViewController, message: String) {
        let vc = UIAlertController(title: "提示",
                                   message: message,
                                   preferredStyle: .alert)
        let okAction = UIAlertAction(title: "确定",
                                     style: .default) { action in
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
        }
        let cancelAction = UIAlertAction(title: "取消",
                                         style: .cancel)
        vc.addAction(cancelAction)
        vc.addAction(okAction)
        
        parent.present(vc, animated: true)
    }
}
